#import pydevd

import pandas
from absl import app, flags

from coin.base.datetime_util import (convert_string_to_dates, iterate_date)
from coin.exchange.bitfinex_v2.kr_rest.product import BitfinexProduct
from coin.exchange.huobi.kr_rest.product import HuobiProduct
from coin.exchange.okex.kr_rest.product import OkexProduct
from coin.experimental.xguo.order_and_feed_stats.logic.query_func import (read_csv_into_df,
                                                                          calculate_volatility)
from coin.experimental.xguo.order_and_feed_stats.app.order_event_stats \
  import OrderEventCSVReader
from coin.proto.coin_order_gateway_pb2 import OrderEvent

FLAGS = flags.FLAGS


def main(argv):
  feed_root = FLAGS.feed_root
  assert feed_root, '--feed_root must be specified.'
  order_event_root = FLAGS.order_event_root
  assert order_event_root, '--order_event_root must be specified.'
  start_date = FLAGS.start_date
  assert start_date, '--start_date must be specified.'
  end_date = FLAGS.end_date
  assert end_date, '--end_date must be specified.'
  order_machine = FLAGS.order_machine
  assert order_machine, '--order_machine must be specified.'
  feed_machine = FLAGS.feed_machine
  assert feed_machine, '--feed_machine must be specified.'
  exchange = FLAGS.exchange
  assert exchange, '--exchange must be specified.'
  market_type = FLAGS.market_type
  assert market_type, '--market_type must be specified.'
  owner = FLAGS.owner
  assert owner, '--owner must be specified.'

  start_date = convert_string_to_dates(start_date)[0]
  end_date = convert_string_to_dates(end_date)[0]
  trading_dates = [td for td in iterate_date(start_date, end_date)]

  interval_sec = 1200
  correlation_matrix = []
  for trading_date in trading_dates:
    order_event_reader = OrderEventCSVReader(order_event_root,
                                             order_machine,
                                             trading_date,
                                             exchange,
                                             owner,
                                             market_type)
    order_event = order_event_reader.read_order_event()
    correlation_dict = {}
    for symbol, oe_df in order_event.items():
      fill_df = oe_df.loc[oe_df['event_type'] == OrderEvent.ORDER_FILLED]
      feed_df = read_csv_into_df(feed_root, feed_machine, trading_date, exchange, symbol)
      volatility = calculate_volatility(feed_df, interval_sec)
      cum_pos = (fill_df['fill_qty'] * fill_df['sign']).cumsum().shift(1).fillna(0)
      fill_df['last_pos'] = cum_pos
      fill_df['prev_price'] = fill_df['fill_price'].shift(1).fillna(0)
      fill_df['pnl'] = (fill_df['fill_price'] - fill_df['prev_price']) * \
                       fill_df['last_pos']
      interval = '%dS' % interval_sec
      resampled_pnl = fill_df['pnl'].resample(interval).sum()
      correlation = volatility.corr(resampled_pnl)
      correlation_dict[symbol] = correlation
    correlation_matrix.append(correlation_dict)
  df = pandas.DataFrame(correlation_matrix, index=trading_dates)
  df = df.T
  formatter = lambda x: '%.2f' % x
  df = df.applymap(formatter)
  print(df.to_string())

  return 0


if __name__ == '__main__':
  flags.DEFINE_string('feed_root', 'feed_csv', 'feed root directory.')

  flags.DEFINE_string('order_event_root', 'order_event', 'order event root directory.')

  flags.DEFINE_string('start_date', None, 'yyyymmdd')

  flags.DEFINE_string('end_date', None, 'yyyymmdd. Feed at end_date is not checked.')

  flags.DEFINE_string('feed_machine', None, 'feed instance machine name.')

  flags.DEFINE_string('order_machine', None, 'order instance machine name.')

  flags.DEFINE_string('exchange', None, 'exchange')

  flags.DEFINE_string('market_type', None, 'Spot, Futures, Margin')

  flags.DEFINE_string('owner', None, '')

  app.run(main)
